
const APPID = require("../../utils/config.js").APPID;
const AgoraMiniappSDK = require("../../lib/Agora_Miniapp_SDK_for_WeChat.js");
const innerAudioContext = wx.createInnerAudioContext()

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    type: {
      type: String,
      value: '1'
    },
    userInfo: {
      type: Object,
      value: {}
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    videoInfo: {
      channel: new Date().getTime().toString(),
      uid: 12
    },
    mediaUrl: '',
    pusherContext: null,
    showCover: false
  },
  methods: {
    initAgoraChannel: function(uid, channel) {
      return new Promise((resolve, reject) => {
        const client = new AgoraMiniappSDK.Client()
        this.subscribeEvents(client);
        this.client = client;
        client.init(APPID, () => {
          client.join(undefined, channel, uid, () => {
              client.publish(url => {
                resolve(url);
              }, e => {
                reject(e)
              });
          }, e => {
            reject(e)
          })
        }, e => {
          reject(e);
        });
      });
    },
    reinitAgoraChannel: function(uid, channel) {
      console.log('重新连接')
      return new Promise((resolve, reject) => {
        const client = new AgoraMiniappSDK.Client()
        this.subscribeEvents(client);
        this.client = client;
        client.init(APPID, () => {
          client.rejoin(undefined, channel, uid, () => {
              client.publish(url => {
                resolve(url);
              }, e => {
                reject(e)
              });
          }, e => {
            reject(e)
          })
        }, e => {
          reject(e);
        });
      });
    },
    subscribeEvents: function(client) {
      client.on("error", err => {
        let code = err.code || 0;
        if (code === 905) {
          this.reconnect();
        }
      });
    },
    reconnect: function() {
      this.client && this.client.destroy();
      this.reconnectTimer = setTimeout(() => {
        const channel = this.data.videoInfo.channel;
        const uid = this.data.videoInfo.uid;
        this.reinitAgoraChannel(uid, channel).then(url => {
          that.setData({
            mediaUrl: url
          })
        }).catch(e => {
          return this.reconnect();
        });
      }, 1 * 1000);
    },
    decline: function() {
      this.triggerEvent('decline', {}, {})
    },
    agreet: function() {
      this.triggerEvent('agreet', {}, {})
    }
  },
  ready: function() {
    wx.setKeepScreenOn({
      keepScreenOn: true
    });

    innerAudioContext.autoplay = false
    innerAudioContext.src = 'https://xyxbtest.oss-cn-shenzhen.aliyuncs.com/public/assets/voip_call.mp3'
    innerAudioContext.loop = true

    this.data.pusherContext = wx.createLivePusherContext(this);
    this.data.pusherContext.start();
    const channel = this.data.videoInfo.channel;
    const uid = this.data.videoInfo.uid;
    const that = this
    this.initAgoraChannel(uid, channel).then(url => {
      that.setData({
        mediaUrl: url
      })
      that.client.muteLocal(
        'video',
        function () {
        },
        function () {
          console.log('错误11')
        }
      )
      innerAudioContext.play()
    }).catch(e => {
      console.log(22, e)
      wx.showToast({
        title: `客户端初始化失败`,
        icon: 'none',
        duration: 2000
      });
    });
  },
  detached: function() {
    innerAudioContext.stop()
    this.client.leave(
      () => {
        console.log('退出成功')
        this.client.destroy(
          () => {
            console.log('销毁成功')
          },
          () => {
            console.log('销毁失败')
          }
        )
      },
      () => {
        console.log('退出失败')
      }
    )
  }
})
